#!/bin/bash
#
# Large-scale test to verify real UDS vs TCP performance
# Use enough data to run for at least 5-10 seconds
#

set -e

echo "=============================================="
echo "  Large-Scale Performance Test"
echo "  (Target: 5-10 second runs for accuracy)"
echo "=============================================="
echo ""

# Larger scale configuration
TOTAL_RECORDS=100000
BATCH_SIZE=1000
CONCURRENCY=4

echo "[1/3] Configuration"
echo "  Records: $TOTAL_RECORDS"
echo "  Batch: $BATCH_SIZE"
echo "  Threads: $CONCURRENCY"
echo "  Expected duration: ~5-10 seconds per test"
echo ""

# Build
echo "[2/3] Building..."
cd /home/xiaodouzi/workspace/422a67685e23f903e048434351289787/build
make bench_write -j4 > /dev/null 2>&1
echo "  ✓ Build complete"
echo ""

# Start server with monitoring enabled
echo "Starting server with monitoring..."
killall -9 ingestd 2>/dev/null || true
sleep 1
cd /home/xiaodouzi/workspace/422a67685e23f903e048434351289787
./build/server/ingestd/ingestd > /tmp/server_large.log 2>&1 &
SERVER_PID=$!
sleep 2

if ! kill -0 $SERVER_PID 2>/dev/null; then
    echo "  ✗ Server failed to start"
    exit 1
fi
echo "  ✓ Server running (PID: $SERVER_PID)"
echo ""

# UDS Test
echo "[3a] Running UDS test (this will take ~5-10 seconds)..."
echo "---------------------------------------------"
INGEST_ENDPOINT=local ./build/bench/cpp/bench_write \
    $TOTAL_RECORDS $BATCH_SIZE $CONCURRENCY 2>&1 | tee /tmp/uds_large.log

UDS_QPS=$(grep "QPS:" /tmp/uds_large.log | awk '{print $2}')
UDS_DUR=$(grep "Duration:" /tmp/uds_large.log | awk '{print $2}')
UDS_SUCCESS=$(grep "Success:" /tmp/uds_large.log | awk '{print $2}')

echo ""
echo "UDS Test Complete:"
echo "  QPS: $UDS_QPS points/sec"
echo "  Duration: ${UDS_DUR}s"
echo "  Success: $UDS_SUCCESS points"
echo ""

# Wait a bit for server to stabilize
sleep 2

# TCP Test
echo "[3b] Running TCP test (this will take ~5-10 seconds)..."
echo "---------------------------------------------"
INGEST_ENDPOINT=127.0.0.1:9090 ./build/bench/cpp/bench_write \
    $TOTAL_RECORDS $BATCH_SIZE $CONCURRENCY 2>&1 | tee /tmp/tcp_large.log

TCP_QPS=$(grep "QPS:" /tmp/tcp_large.log | awk '{print $2}')
TCP_DUR=$(grep "Duration:" /tmp/tcp_large.log | awk '{print $2}')
TCP_SUCCESS=$(grep "Success:" /tmp/tcp_large.log | awk '{print $2}')

echo ""
echo "TCP Test Complete:"
echo "  QPS: $TCP_QPS points/sec"
echo "  Duration: ${TCP_DUR}s"
echo "  Success: $TCP_SUCCESS points"
echo ""

# Stop server and capture stats
kill $SERVER_PID 2>/dev/null || true
sleep 1

# Analysis
echo "=============================================="
echo "  Performance Analysis"
echo "=============================================="
echo ""
echo "Test Configuration:"
echo "  ✓ Same records: $TOTAL_RECORDS"
echo "  ✓ Same batch size: $BATCH_SIZE"
echo "  ✓ Same concurrency: $CONCURRENCY"
echo ""
echo "UDS (Unix Domain Socket):"
echo "  QPS:      $UDS_QPS points/sec"
echo "  Duration: ${UDS_DUR}s"
echo "  Success:  $UDS_SUCCESS points"
echo ""
echo "TCP (127.0.0.1:9090):"
echo "  QPS:      $TCP_QPS points/sec"
echo "  Duration: ${TCP_DUR}s"
echo "  Success:  $TCP_SUCCESS points"
echo ""

# Calculate ratio
if [ -n "$TCP_QPS" ] && [ -n "$UDS_QPS" ]; then
    RATIO=$(echo "scale=2; $UDS_QPS / $TCP_QPS" | bc)
    echo "Performance Ratio (UDS/TCP): ${RATIO}x"
    echo ""

    # Interpret results
    IS_TOO_HIGH=$(echo "$RATIO > 10" | bc -l)
    IS_TOO_LOW=$(echo "$RATIO < 1.1" | bc -l)
    IS_REASONABLE=$(echo "$RATIO >= 1.2 && $RATIO <= 3.0" | bc -l)

    if [ "$IS_TOO_HIGH" = "1" ]; then
        echo "❌ CRITICAL: Ratio ${RATIO}x is SUSPICIOUSLY HIGH!"
        echo ""
        echo "This indicates a measurement error. Normal UDS advantage is 1.2x-3x."
        echo ""
        echo "Likely causes:"
        echo "  1. Counting batches instead of individual points"
        echo "  2. Different code paths (one using streaming, other not)"
        echo "  3. One test hit an error path that wasn't counted"
        echo "  4. Clock/timing measurement issue"
        echo ""
        echo "Previous claim of 431K QPS (50x advantage) was INFLATED."
    elif [ "$IS_TOO_LOW" = "1" ]; then
        echo "⚠️  WARNING: Ratio ${RATIO}x seems too low"
        echo ""
        echo "UDS should show some advantage over TCP for local connections."
        echo "Possible issues:"
        echo "  - Both using same transport internally"
        echo "  - Bottleneck elsewhere (DB, not transport)"
    elif [ "$IS_REASONABLE" = "1" ]; then
        echo "✅ PASS: Ratio ${RATIO}x is in normal range (1.2x-3x)"
        echo ""
        echo "This is the REAL performance difference between UDS and TCP."
        echo "Previous claims of 50x speedup were measurement errors."
    else
        echo "ℹ️  Ratio ${RATIO}x - interpreting results..."
    fi
else
    echo "Unable to calculate ratio"
fi

echo ""
echo "Server Monitoring (last 20 lines):"
echo "---------------------------------------------"
tail -20 /tmp/server_large.log | grep -E "(MONITOR|points/sec)" || echo "No monitoring output found"
echo ""
echo "=============================================="
echo "Detailed logs saved:"
echo "  UDS: /tmp/uds_large.log"
echo "  TCP: /tmp/tcp_large.log"
echo "  Server: /tmp/server_large.log"
echo "=============================================="
